import React,{Component} from 'react';
import {View,Text,ScrollView,TouchableOpacity,Image,Modal,BackHandler,ToastAndroid,FlatList} from 'react-native';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import dwstyles from './styles';
import {naviPush} from '../../navigatorApp/actions';
import {connect} from 'react-redux';
import themeconfig from '../../config/theme';
import Search from 'react-native-search-box';
import styles from '../historylist/styles'
import {toast, getConfig} from '../../utils/NativeUtil'
import {GetAllDepartment} from './actions'
import NavBarCommon from '../../component/NavBarCommon'
import {GetDepartMenber} from '../dwjs2/actions'
import {naviHeight, paddingTop} from '../../utils/ScreenUtil'

let pageIndex = 0;
let hasMore = false;
let flag = false;
class DWJS extends Component {

    // static navigationOptions = ({ navigation, screenProps }) => ({
    //     header: <CLNavigatorHeader navigation={navigation} title="队伍建设" leftAction={params.backAction}/>
    // });

    static navigationOptions = ({navigation, screenProps}) => {
        const {params = {}} = navigation.state;
        let header = <CLNavigatorHeader navigation={navigation} title="队伍建设" leftAction={params.backAction}/>;
        return {header};
    };

    componentDidMount() {
        // this.props.navigation.setParams({backAction: this._backAction});
    }

    _backAction = () => {
        // 判断是否为最上层
         console.log(flag)
         if (flag) {
         } else {
            this.props.naviBack();
         }
    }

    render(){
        return <DWJS_fu laiyuan='home' {...this.props} />
    }
}


class DWJS_fu extends Component {
    constructor(props){
        super(props);
        console.log(props);
        this.state={
            m1:false,
            flag:false,
            title:'',
            exit:false,
            i1:0,
            listitem:[],
            listitem2:[],
            data:[],
            isLoading: true,
            refreshing:false,
            searchText:'',
            searchlist:false
        },
        this._data=[];
    }
    


    componentDidMount(){
        var loginid='';
        var keywords='';
        var userguid ='';
        getConfig('c1_text',res => {loginid=res.c1_text});
        console.log('loginid',loginid)
        getConfig('c2_text',res => {keywords=res.c2_text});
        console.log('keywords',keywords);
        getConfig('userguid',res => {userguid=res.userguid});
        console.log('userguid',userguid);
        let params = {
            LoginID : loginid,
            KeyWords : keywords,
            UserGuid : userguid
        }
        console.log('params',params);
        GetAllDepartment(params).then(res=>{
            console.log('res',res);
            this.setState({
                listitem:res
            })
        }).catch(msg=>{
            console.error(msg)
        });
    }

    getData=()=>{
        let params={
            SearchText : this.state.searchText,
            DeptCode : '',
            PageIndex : pageIndex
        }
        GetDepartMenber(params).then(res=>{
            console.log(res);
            if (res.length < 10) {
                hasMore = false
            } else {
                hasMore = true
            }
            if (pageIndex == 0) {
                this._data = res;
            } else {
                this._data = this._data.concat(res);
            }
            if(res.length>0){
            this.setState({
                data:this._data,
                isLoading: false,
                refreshing: false,
            })
        }
        }).catch(msg=>{
            console.log(msg);
        })
    }
    componentWillUnmount(){
        this.setState({
            listitem2:[]
        })
    }

    onEndReached = () => {
        if (hasMore) {
            pageIndex++;
            this.getData()
        }
    }

    onRefresh = () => { //刷新回调函数
        this.setState({
            refreshing: true,
            isLoading: true
        })
        pageIndex = 0;
        this.getData()
    }



    _keyExtractor = (item, index) => index;

    _listfooter=()=>{
        return (
            <View style={dwstyles.footerimg}>
            <Image source={require('../../image/pic_stop.png')} style={{width:'50%',height: 90 ,marginTop: 20}}/>
            </View>
        )
    }

    _loading=()=>{
        return(
            <View style={dwstyles.footerimg}>
            <Text>isLoading...</Text>
            </View>
        )
    }

    _renderItem=({item,index})=>{
        return(
            <TouchableOpacity onPress={(i)=>{i=index;console.log('index',i);this.props.naviPush('MemberInfo',{userguid:this.state.data[i].UserGuid})}}>
            <View style={dwstyles.listitem}>
                <Image source={item.Sex=='男'?require('../../image/ico_man.png'):require('../../image/ico_women.png')} style={{width:30,height:30}} />
                <View style={dwstyles.rightContent}><Text style={dwstyles.rightContent_text}>{item.DisplayName}</Text><Text>{item.Mobile}</Text></View>
            </View>
            </TouchableOpacity>
        )
    }

    toUserDetail = (i) => {
        console.log('i',i)
        this.props.naviPush('DWJS2',{teaminfo:i,abovelevel:this.state.listitem[this.state.i1]});
        this.setState({m1:false});
    }

    press1=(i , itt)=>{
        console.log('i',i);
            let g = [];
            let flist = this.state.listitem;
            let infocode = this.state.listitem[i].InfoCode
            //找到对应ISDep的项，将这些项推进listitem2这个数组里
            for(var j=0;j<flist.length;j++){
                if(flist[j].ISDep==infocode){
                    g.push(flist[j]);
                    this.setState({
                        i1:i,
                        listitem2: g
                    })
                }
            }
            if (g.length == 0) {
                // 直接跳转
                this.props.naviPush('DWJS2',{teaminfo:this.state.listitem[i],
                    abovelevel:this.state.listitem[this.state.i1]});
                    return
            } else {
                this.setState({flag:true,title:itt.InfoName});
                flag = true
            }
    }

    handleSearch=(e)=>{
        console.log(e);
        pageIndex=0;
        this.setState({
            searchText:e,
            searchlist:true
        })
        this.getData()
    }

    handleCancel=()=>{
       console.log('cancel')
       pageIndex =0;
       this.setState({
           searchlist:false,
           searchText:''
       })
       this.getData()
    }


    handleFirstDep = ( item ,  index) => {
        this.press1(index , item);
    }

    render(){


        let topview = undefined;
        if (this.props.laiyuan != 'home'){
            topview = <NavBarCommon  
            customStyle={{
                borderBottomWidth: 0,
                backgroundColor: 'white'
            }}
            rightTitle=""
            title="队伍建设"
            ></NavBarCommon>
        }else{
            topview = <View style={{height:paddingTop}}></View>
        }

        return(
            <View style={dwstyles.totalbox}>
            {topview}
            {/*上面根据点击的入口来判断要不要显示导航栏*/}
            <Search backgroundColor='#eee' placeholder='搜索队员' inputBorderRadius={18} searchIconCollapsedMargin={45} placeholderCollapsedMargin={33} inputStyle={{backgroundColor:themeconfig.grey3Color,width:'80%'}} cancelButtonTextStyle={{color:themeconfig.grey2Color}} onSearch={e=>this.handleSearch(e)} onCancel={this.handleCancel} cancelTitle='取消'/>
            <View style={[styles.Titleline,{display:this.state.flag?'flex':'none'}]}>
                <Text style={[styles.Titleline_text1,{fontSize:16,borderBottomWidth:0,color:themeconfig.grey2Color,paddingBottom:10}]} onPress={()=>{this.setState({flag:false}) , flag=false}}>{this.state.title}</Text>
            </View>
            <View style={{display:this.state.searchlist?'flex':'none'}}>
                <FlatList data={this.state.data} renderItem={this._renderItem} keyExtractor={this._keyExtractor} ListFooterComponent={this.state.isLoading ? this._loading:this._listfooter} onEndReached={this.onEndReached} onEndReachedThreshold={0.2} onRefresh={this.onRefresh} refreshing={this.state.isLoading}/>
            </View>
            {/*上面的view为搜索功能，点击搜索时隐藏队伍建设列表，显示搜索结果*/}

            <ScrollView style={{display:this.state.searchlist?'none':this.state.flag?'none':'flex'}}>
            {this.state.listitem.map((item,index)=>{
                if(item.ISDep=='1'){
                return(
                <TouchableOpacity onPress={()=>this.handleFirstDep( item , index)} key={index}>
                <View style={dwstyles.listitem}>
                    <Image source={require('../../image/ico_close.png')} style={{width:30,height:30}} />
                    <View style={dwstyles.rightContent}><Text style={dwstyles.rightContent_text}>{item.InfoName}</Text></View>
                </View>
                </TouchableOpacity>
                )}
            }
            )
            }
            </ScrollView>
            {/*上面为一级列表*/}

            <ScrollView style={[dwstyles.view2,{display:this.state.searchlist?'none':this.state.flag?'flex':'none'}]}>
                  {this.state.listitem2.map((item,index)=>{
                      return <TouchableOpacity key={index} onPress={(i) => {i=item;this.toUserDetail(i)}}>
                    <View style={dwstyles.listitem2}>
                      <Text>{item.InfoName}</Text>
                      <Image source={require('../../image/icon_right.png')} style={{width:20,height:20}}/>
                  </View>
                </TouchableOpacity>
                })}
            </ScrollView>
            {/*上面为二级列表 */}
            </View>
        )
    }
}

const mapStateToProps = state => ({

});

const mapDispatchToProps = dispatch => ({
    naviPush: (routeName, params) => {
        dispatch(naviPush(routeName, params));
    },
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(DWJS);
